# --*--coding:utf-8 --*--

import warnings
warnings.filterwarnings("ignore")
import requests
import json
# from multiprocessing import Pool
# from multiprocessing.dummy import Pool
import random
import time

def CheTu(search_info):

	''' 车图:抓取手淘hot标签图片'''

	url = 'https://s.m.taobao.com/search' # WX端数据
	head = {
			'Host': 's.m.taobao.com',
			'Connection': 'keep-alive',
			'Pragma': 'no-cache',
			'Cache-Control': 'no-cache',
			'Accept': 'application/json',
			'X-Requested-With': 'XMLHttpRequest',
			'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1',
			'Accept-Encoding': 'gzip, deflate, br',
			'Accept-Language': 'zh-CN,zh;q=0.9'
			}

	payload = {
			'q':search_info['keyword'],
			'search':'提交',
			'tab':'all',
			'sst':'1',
			'n':'20',
			'buying':'buyitnow',
			'm':'api4h5',
			'abtest':'11',
			'wlsort':'11',
			'page':''
		}

	urlList = []
	try:
		for page in range(search_info['pagenumber']+1):
			payload['page'] = page
			resp = requests.get(url,params = payload,verify=False,headers = head)
			try:
				goodsList = resp.json()['listItem']
				for goods in goodsList:
					if goods['isP4p'] == 'true':
						img2 = "http:" + goods['img2']    # http://img.alicdn.com/imgextra/i3/17722666/O1CN011VZ4NqqRf6Xun2U_!!0-saturn_solar.jpg
						goodsurl = "https://item.taobao.com/item.htm?id=" + goods['item_id']
						urlList.append({"imgurl":img2,"page":page,"position":goodsList.index(goods)+1,"title":goods['name'],"goodsurl":goodsurl})
						time.sleep(random.uniform(0.5,1))
			except:
				pass
		return {"status": True, "result": urlList}
	except:
		return {"status": True, "result":"网络不稳定，请重新爬取！"}



if __name__ == '__main__':
	
	search_info = {"keyword":"女包","pagenumber":2}
	print (CheTu(search_info))
